package br.com.salao.ejb.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import br.com.salao.ejb.dao.EnderecoDao;
import br.com.salao.entity.Endereco;

public class EnderecoDaoImpl implements EnderecoDao{
	
	private final GenericDao<Endereco> dao;
	private EntityManager em;
	private Logger logger = Logger.getLogger(EnderecoDaoImpl.class.getName());
	
	public EnderecoDaoImpl(EntityManager em){
		this.em = em;
		dao = new GenericDao<Endereco>(em, Endereco.class);
	}
	
	public Endereco inserir(Endereco endereco){
		return dao.salvar(endereco);		
	}
	
	public Endereco update(Endereco endereco){
		return dao.update(endereco);		
	}
	
	public void deletar(int id){
		dao.deletar(id);		
	}
	
	public Endereco buscarEnderecoPorLogradouro(Endereco endereco){
		
		Endereco enderecoBD = null;
		
		try {		
			Query query = em.createQuery("from Endereco e where e.logradouro = :logradouro and e.numero = :numero ");
			query.setParameter("logradouro", endereco.getLogradouro());
			query.setParameter("numero", endereco.getNumero());
			enderecoBD = (Endereco) query.getSingleResult();	
			
		} catch (Exception e) {
			enderecoBD = null;
			StringBuffer sb = new StringBuffer();
			sb.append(e.getMessage() + "\n");

			logger.error(sb.toString());
		}
		return enderecoBD;
	}
	
	@SuppressWarnings("unchecked")
	public List<Endereco> buscarBairrosDeEstabelecimentosCadastrados(int idCidade){

		List<Endereco> enderecos = new ArrayList<Endereco>();

		try {
			
			Query query = em.createQuery("from Endereco e where e.bairro.cidade.id = :idCidade and b.isEstabelecimento = true");
			query.setParameter("idCidade", idCidade);
			enderecos = (List<Endereco>)query.getResultList();
			
		} catch (Exception e) {
			
			StringBuffer sb = new StringBuffer();
			sb.append(e.getStackTrace() + "\n");
			sb.append(e.getCause() + "\n");
			sb.append(e.getMessage() + "\n");

			logger.error(sb.toString());

			e.printStackTrace();
		} 
		return enderecos;

	}	
	
}
